import React, {Component} from 'react'
import {inject, observer} from "mobx-react";
import {withRouter} from 'react-router-dom';
import {RouteLayout, ListAdvanced} from 'weaver-mobile-page';
import {List, Tools, Toast, TextareaItem,
    Picker, Icon, Flex, Button } from "weaver-mobile";
import '../../../style/signlog/update.less'
import * as commonUtil from "../../../util/CommonUtil";
import {toJS} from 'mobx';
import SignInput from '../public/SignInput'
import * as mobx from "mobx";

const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;

@withRouter
@inject("odocComsStore", "updateSignLogStore")
@observer
export default class Index extends Component {
    constructor(props) {
        super(props);
        this.state={
        }
    }

    componentWillMount() {
        const {updateSignLogStore, location={}, odocComsStore} = this.props;
        const {init} = updateSignLogStore;
        const {pathname} = location;
		let {requestParam = {}} = odocComsStore;
		requestParam = mobx.toJS(requestParam);
		delete requestParam.markInfo;
        init(pathname, [], requestParam);
        window.onresize = ()=>{
			this.updateHeight();
		}
    }

    componentWillUnmount() {
        const {updateSignLogStore} = this.props;
        const {destory} = updateSignLogStore;
        typeof destory == "function" && destory();
    }

    shouldComponentUpdate() {
        const {updateSignLogStore, odocComsStore = {}} = this.props;
        const {savenumber = 0} = updateSignLogStore;
        if (savenumber > 0) {
            const {submitCallBack} = odocComsStore;
            odocComsStore.onClose = submitCallBack;
        }
        return true;
    }

    render() {
        return (
            <div className={"updateContent"}>
                <div className={"update-Btn"}>
                    {this.getTopBtn()}
                </div>
                {this.getSignListContent()}
                {this.getSignInputContent()}
                <ButtonGroup
                    data={this.getButtons()}
                    flexStyles={this.getFlextStyles()}
                />
            </div>
        )
    }

    updateHeight = () =>{
		let listHeight = document.body.clientHeight || document.documentElement.clientHeight;
		listHeight = listHeight -41;
		if (listHeight != this.state.listHeight) {
			this.setState({listHeight});
		}
    }

    getTopBtn = () => {
        const {updateSignLogStore, history} = this.props;
        const {listAd} = updateSignLogStore;
        const {searchAdvancedStore = {}} = listAd;
        const {route, id} = searchAdvancedStore;

        return [
            <Button  onClick={() => {
                history.push({
                    pathname: route + "/" + id,
                    state: {dialogType: 1, title: getLabel(347, "高级搜索")}
                });
            }}><Icon key="filter-o" type="filter-o" size={'sm'} style={{"vertical-align": "middle"}}/></Button>,
        ]
    }

    /**
     * 签字意见组件
     * @returns {null}
     */
    getSignInputContent = () => {
        const {updateSignLogStore, odocComsStore} = this.props;
        const {isShowSignInput = false, hiddenSignInput, sumitParams,
            appendPickerRemark, changeSubmitParams} = updateSignLogStore;
        const {remark = ""} = sumitParams;
        const {workflowStores = {}} = odocComsStore;
        let signparams = {
            workflowStores,
            remark,
            changeRemark:changeSubmitParams,
            appendRemark:appendPickerRemark,
        };

        return isShowSignInput ?
            <div className={"maskSign updateSign"}>
                <div className="wf-signView-panel-mask"
                     onClick={() => {
                         hiddenSignInput()
                     }}
                ></div>
                <div className="wf-signView-panel-content">
                    <SignInput {...signparams}/>
                </div>
            </div> : null;
    }

    /**
     * 签字意见列表组件
     * @returns {*}
     */
    getSignListContent = () => {
        const {updateSignLogStore} = this.props;
        const {listAd, coreParams} = updateSignLogStore;

        return <ListAdvanced
            withSwipeAction
            swipeActionProps={this.getSwipeActionProps()}
            className={"updateLogList"}
            rowKey={"logid"}
            treeKey={"logid"}
            store={listAd}
            hasAdvanceSerach
            showSearchBar={false}
            renderSeparator={this.renderSeparator}
            conditionFetchOptions={ {url: "/api/odoc/signInputUpdate/getSignLogForm",  method: "POST",  params: {...coreParams},} }
            onSearch={this.onSearch}
            getTemplate={(template) => {
                return ({json: this.getTemplate()})
            }}
        />
    }
    onSearch = () => {
        const {updateSignLogStore} = this.props;
        const {reload} = updateSignLogStore;
        reload();
    }

    getTemplate =  () => {
        const template1 = [
            {
                key: 'col1',
                configs: [
                    {
                        key: 'row1',
                        render: (data, value, index) => {
                            const {operatorspan, operator, operatorDeptspan="", remarkspan, remark,
                                nodeidspan, nodeid, logtypespan, logtype, operatedatespan,
                                operatedate} = data;
                            return <div className={"list_row1_item"}>
                                <div className={"operator list_item"}>
                                    <span className={"title"}>{getLabel(99, "操作者")+":"}</span>
                                    <span className={"content"}>{operatorspan || operator}</span>
                                </div>
                                <div  className={"list_item"}>
                                    <span className={"title"}>{getLabel(385898, "操作者部门")+":"}</span>
                                    <span className={"content"}>{operatorDeptspan}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(15503,"操作类型")+":"}</span>
                                    <span className={"content"}>{logtypespan || logtype}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(519984,"操作环节")+":"}</span>
                                    <span className={"content"}>{nodeidspan || nodeid}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(17614,"签字意见")+":"}</span>
                                    <span className={"content"}>{remarkspan}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(15502, "操作时间")+":"}</span>
                                    <span className={"content"}>{operatedatespan || operatedate}</span>
                                </div>
                            </div>
                        }
                    },
                ],
            },
        ]
        return template1;
    }

    /**
     * 按钮数据
     * @param section
     * @param index
     * @returns {*}
     */
    renderSeparator = (section, index) => {
        const {updateSignLogStore} = this.props;
        const {listAd = {}} = updateSignLogStore;
        const {listViewStore = {}} = listAd;
        const data = toJS(listViewStore.data)[index];
        return (
            <div key={`${section}_${index}`} className={"list-btns-wrap"}>
                <span onClick={() => this.doDeleteSignLogByLogId(data)}><Icon type={"delete"} size={"xs"} />{getLabel(91, "删除")}</span>
                <span onClick={() => this.doUpdateSignLogByLogId(data)}><Icon type={"edit"} size={"xs"} />{ getLabel(103, '修改')}</span>
            </div>
        );
    }

    /**
     * 滑动按钮
     * @returns {{right: *[]}}
     */
    getSwipeActionProps = () => ({
        right: [
            {
                text: getLabel(103, '修改'),
                onPress: this.doUpdateSignLogByLogId,
                className: 'swipeMove'
            }, {
                text: getLabel(91, "删除"),
                onPress: this.doDeleteSignLogByLogId,
                className: 'swipeDelete'
            },
        ],
    })

    /**
     * 修改签字意见
     * @param data
     */
    doUpdateSignLogByLogId = (data) => {
        if (data && (data.logid || data.id)) {
            const {updateSignLogStore} = this.props;
            const {getSignInput} = updateSignLogStore;
            getSignInput(data)
        } else {
            Toast.fail(getLabel(1, "请选择需要修改的数据！"))
        }
    }

    /**
     * 删除签字意见
     * @param data
     */
    doDeleteSignLogByLogId = (data = {}) => {
        if (data && (data.logid || data.id)) {
            const {updateSignLogStore} = this.props;
            const {doDeleteSignLogByLogId} = updateSignLogStore;
            const {nodeidspan, nodeid, operatorspan, operator} = data;
            let confmsg = getLabel(520073, '确定要删除${userName}在"${nodeName}"环节的操作意见吗？');
            confmsg = confmsg.replace("\${userName}", "<span class='confimuser'>"+(operatorspan || operator)+"</span>")
            confmsg = confmsg.replace("\${nodeName}", nodeidspan || nodeid)
            //确定要删除 谢大海 在“审批”环节的操作意见吗？
            commonUtil.showConfirm({
                content: <span dangerouslySetInnerHTML={{__html:confmsg}}/>,
                okEvent: () => {
                    doDeleteSignLogByLogId(data)
                },
            })
        }
    }

    /**
     * 取消
     */
    onCancel = (res = {}) => {
        const {api_status = false} = res;
        const {updateSignLogStore, odocComsStore = {}} = this.props;
        const {destory, isShowSignInput = false, hiddenSignInput, savenumber = 0} = updateSignLogStore;
        if (isShowSignInput) {//返回列表
            hiddenSignInput()
        } else {
            typeof destory == "function" && destory();
            if (savenumber > 0) {
                const {submitCallBack} = odocComsStore;
                typeof submitCallBack == "function" && submitCallBack()
            }
            window && window.historyRoute && window.historyRoute.go && (window.historyRoute.go(-1));
        }
    }

    /**
     * 提交
     */
    onSubmit = () => {
        const {updateSignLogStore} = this.props;
        const {doSave, sumitParams={}} = updateSignLogStore;
        let params = {}

        const {nodeidspan, nodeid, operatorspan, operator} = sumitParams;
        let confmsg = getLabel(520074, '确定要修改${userName}在"${nodeName}"环节的操作意见吗？');
        confmsg = confmsg.replace("\${userName}", "<span class='confimuser'>"+(operatorspan || operator)+"</span>")
        confmsg = confmsg.replace("\${nodeName}", nodeidspan || nodeid)
        //确定要删除 谢大海 在“审批”环节的操作意见吗？
        commonUtil.showConfirm({
            content: <span dangerouslySetInnerHTML={{__html:confmsg}}/>,
            okEvent: () => {
                doSave(params, this.onCancel)
            },
        })
    }

    /**
     * 显示按钮样式
     * @returns {{style: {flex: number}}[]}
     */
    getFlextStyles = () => {
        const flextStyles = [
            {
                style: {flex: 1}
            }, {
                style: {flex: 1}
            }
        ];
        return flextStyles;
    }

    /**
     * 底部按钮
     * @returns {Array}
     */
    getButtons = () => {
        const {updateSignLogStore} = this.props;
        const {loading = false, isShowSignInput = false} = updateSignLogStore;
        let buttons = [];
        isShowSignInput && buttons.push({
            key: 'close',
            text: getLabel(31129, "取消"),
            onClick: this.onCancel,
        });
        isShowSignInput && buttons.push({
            key: 'submit',
            text: getLabel(501196, "确定"),
            onClick: this.onSubmit,
            type: 'primary',
            disabled: !loading,
        });
        return buttons;
    }
}